package com.shixu.framework.plugins.dictionary.web.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shixu.framework.plugins.dictionary.DictionaryHelper;
import com.shixu.framework.plugins.dictionary.domain.Dictionary;
import com.shixu.framework.util.JsonUtils;
import com.shixu.framework.util.StringUtils;

@Controller
public class DictAjaxController {

	@Autowired
	private DictionaryHelper dictionaryHelper;
	

	@RequestMapping(value="/api/dict/loadDicts" ,method = {GET})
	@ResponseBody
	public String loadDicts(HttpServletRequest request,HttpServletResponse response){
		
		String type = request.getParameter("t");
		String parentKey = request.getParameter("p");
		String typeArr[] = {type};
		if (StringUtils.indexOf(type, ",") > 0) {
			 typeArr = StringUtils.split(type, ",");
		}
		
		List<Dictionary> items = new ArrayList<Dictionary>();
		for (int i = 0; i < typeArr.length; i++) {
			Map<String, Dictionary> dictMap = dictionaryHelper.getDictionariesByTypeAndParent(typeArr[i], parentKey);
			items.addAll(dictMap == null ? new ArrayList<Dictionary>(0) : new ArrayList<Dictionary>(dictMap.values()));
		}
		
		String json = JsonUtils.toJson(items);
		return json;
	}
}
